<style lang="less">

.state_50 {
  opacity: 0.4;
}

//完成
.state_3 {
  border: 1px solid greenyellow;
}

.licointaiunuer {
  ::v-deep {
    .v-md-editor-preview {
      padding: 0px;
    }
  }

}
</style>
<template>
  <div>
    <erpForm :props_cols="cols_data" :props_ignore_cols="['taskcontent', 'plan_endtime', 'state', 'plan_work_time']"
             :model="formData" ref="formRef" label-width="auto">
      <el-form-item label="要求交付时间">
              <span style="cursor: pointer;margin-right: 5px;" @click="() => {
            formData['plan_endtime'] = dateFormatYYYYMMDDHHmmss(moment(formData['plan_endtime'] || new Date()).add(-1, 'd'))
          }">上一天</span>
        <erp-date-picker v-model="formData['plan_endtime']"></erp-date-picker>
        <span style="cursor: pointer;margin-left: 5px;" @click="() => {
                  formData['plan_endtime'] = dateFormatYYYYMMDDHHmmss(moment(formData['plan_endtime'] || new Date()).add(1, 'd'))
               }">下一天</span>
      </el-form-item>


      <el-form-item label="预计消耗时间(d)">
        <el-input type="input" v-model="formData['plan_work_time']"></el-input>
      </el-form-item>

      <el-form-item label="状态">
        <dic-select style="width: 120px;" code="task_state" type="input" v-model="formData['state']"></dic-select>
      </el-form-item>

      <el-form-item label="任务内容(大型)" v-if="loadingcom" style="width: 100%;">
        <el-input type="textarea" v-model="formData.taskcontent" style="width: 100%;" :rows="5"></el-input>
      </el-form-item>

      <div>
        <h3>明细</h3>
      </div>
      <div style="margin-bottom: 5px;;">
        <el-button type="primary" @click="() => { triggerAddRow() }">新增</el-button>
      </div>

      <ul>

        <li class="licointaiunuer " v-for="(detalitem,index) in detailsList"
            style="display:flex;margin-bottom:10px;border-bottom: 1px solid #ddd;padding-bottom: 10px;">
          <div style="padding-top: 4px;">
      <span style='padding-right:5px' @click="()=>{
        swapAdjacentElements(detailsList,index)
      }">上</span>
            <span style='padding-right:5px'
                  @click="()=>{
        swapNextElements(detailsList,index)
      }"
            >下</span>


          </div>
          <div style="flex:1;display:flex;align-items:center;">
            <div style="height: 120px;overflow: hidden;width: 100%;">
              <mdEditor ref="editRef" :content="detalitem.taskcontent"
                        style="overflow: auto;width: 100%;height: 120px;"
                        :mode="'preview'"></mdEditor>
            </div>

            <!--      <el-input type="textarea" v-model="detalitem.taskcontent" style="width: 100%;" :rows="4" />-->
            <span style="padding-left:10px;cursor: pointer;width:66px;" @click="() => {
                      triggerExpand(detalitem,index)
                  }">展开</span>
          </div>
          <div style="width:100px;margin-right:5px;display:flex;align-items:center"
               :class="`state_${detalitem.state}`"
          >
            <dic-select style="width: 100px;" code="task_state" type="input" v-model="detalitem.state"
            ></dic-select>
          </div>
          <div style="width:120px;display:flex;align-items:center">
            <el-button type="text" @click="()=>deleterow(detalitem,index)">删除</el-button>
          </div>

        </li>


      </ul>


    </erpForm>
  </div>
</template>
<script>
import mdEditor from '@/components/mdEditor/index.vue';
import erpDic from '@/components/dicSelect/dicSelect.vue';
import erpDatePicker from '@/components/erp-date-picker/erp-date-picker.vue';
import erpForm from '@/components/erpform/erpform.vue';
import { cols_data, baseFormData } from './_utils';
import { cloneDeep as deepClone } from 'lodash-es';
import { alertWithPaylod } from '@/utils/alertUtils';
import axios from 'axios';
import moment from 'moment';
import { alertConfirm } from '../../utils/alertUtils';
import { dateFormatYYYYMMDDHHmmss } from '@/utils/index.js';
import { loadScript, loadCss } from '@/utils/loadscript.js';
import FormDialog from '@/components/FormDialog';
import jquery from 'jquery';


function swapAdjacentElements(arr, index) {
  if (index > 0 && index < arr.length) {
    [arr[index], arr[index - 1]] = [arr[index - 1], arr[index]];
  }
}

function swapNextElements(arr, index) {
  if (index < 0 || index >= arr.length - 1) {
    return;
  }

  [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
}


export default {
  components: {
    erpDic,
    erpDatePicker,
    erpForm,
    mdEditor,

  },
  data() {
    return {
      swapNextElements,
      swapAdjacentElements,
      loadingcom: false,
      dateFormatYYYYMMDDHHmmss,
      moment: moment,
      cols_data,
      formData: deepClone(baseFormData),
      detailsList: [],
    };
  },
  methods: {
    dateFormatYYYYMMDDHHmmss,
    async initByDialog(_data) {


      this.loadingcom = true;


      if (_data && _data.id) {
        var one_rs = await axios
            .post('/api/tb_task/apis', {
              _name: 'getbyitem',
              module: '',
              id: _data?.id,
            })
            .then((res) => res.data);
        this.formData = _data;
        console.log('=>(modify.vue:71) this.formData', this.formData);
        await this.$refs['formRef'].initByDialog({ formData: one_rs?.data });
        //获取多个明细任务
        this.detailsList = one_rs?.data?.detailsList;
        console.log('获取多个明细任务 this.detailsList :', this.detailsList);
      }


      this.$nextTick(() => {
        this.fixedcss();
      });


    },
    fixedcss() {
      jquery('.vuepress-markdown-body').css('padding', '0px');
    },

    async triggerExpand(row, index) {
      var resuilt = await FormDialog({
        title: '编辑',
        width: '1000px',
        data() {
          return {
            taskcontent: row?.taskcontent,
          };
        },
        components: {
          modify: () => import('./editcontentdialog.vue'),
        },
      });
      if (resuilt && resuilt.success) {
        row.taskcontent = resuilt?.data;
      }
    },
    initEditRef() {
      this.$refs['editRef'] &&
      this.$refs['editRef'].initByDialog &&
      this.$refs['editRef'].initByDialog({
        html: this.form && this.form.msgContent,
      });
    },
    async deleterow(row, index) {
      await alertConfirm('确定删除吗？');
      var result = await axios.post('/api/tb_task/apis', {
        _name: '删除',
        module: '',
        id: row?.id,
      })
          .then((res) => res.data);

      this.detailsList.splice(index, 1);

    },

    triggerAddRow() {
      var one = {
        taskcontent: '',
        id: '', taskname: '', state: '',
      };
      this.detailsList.push(one);
    },


    async submitByDialog() {
      var paramsresult = this.$refs['formRef'].submitByDialog();
      if (!paramsresult?.success) {
        return paramsresult;
      }
      var parmas = {
        ...paramsresult?.data,
        ...this.formData,
      };
      parmas.taskcontent = this.$refs['editRef']?.$data?.editorValue;

      var detailsList = this.detailsList || [];
      for (let index = 0; index < detailsList.length; index++) {
        detailsList[index].order_num = (index + 1);

      }
      parmas.detailsList = detailsList;


      var resylt = await axios
          .post('/api/tb_task/apis', {
            _name: 'addorupdate',
            ...parmas,
          })
          .then((res) => res.data);
      console.log('resylt :', resylt);
      alertWithPaylod(resylt);

      if (resylt?.success) {
        var id = resylt?.data?.id;
        if (id) {
          this.initByDialog({ id: id });
        }

      }

      return resylt;
    },
  },
};
</script>
